/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mirac
 * Date: 2025-08-25
 * Time: 13:11
 */
public class Solution {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }
    }

    public String tree2str(TreeNode root) {
        if (root == null) return null;
        StringBuilder stringBuilder = new StringBuilder();
        func(root,stringBuilder);
        return stringBuilder.toString();
    }
    public void func(TreeNode root,StringBuilder stringBuilder) {
        if (root == null) return;
        stringBuilder.append(root.val);

        if (root.left != null) {
            stringBuilder.append("(");
            func(root.left,stringBuilder);
            stringBuilder.append(")");
        }else {
            if (root.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        if (root.right != null) {
            stringBuilder.append("(");
            func(root.right,stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}
